package cn.sinata.wanglin.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBMyHelper extends SQLiteOpenHelper {
	private static DBMyHelper instance;
	private Context mContext;
    public DBMyHelper(Context context) {
        super(context, "wanglin_db", null, 1);
       this.mContext=context;
      
    }
    public static DBMyHelper getInstance(Context context) {
		if (instance == null) {
			instance = new DBMyHelper(context.getApplicationContext());
		}
		return instance;
	}
    /**
     * 数据库第一次创建时调用
     * */
    @Override
    public void onCreate(SQLiteDatabase db) {
    	Log.e("数据库第一次创建时调用-->", "onCreate");
        if (!tabIsExist("city", db)) {
            executeAssetsSQL(db, "city.sql");
            System.out.println("创建表：city");
        }
        if (!tabIsExist("province", db)) {
            executeAssetsSQL(db, "province.sql");
            System.out.println("创建表：province");
        }
    }
 
    /**
     * 数据库升级时调用
     * */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 数据库不升级
        if (newVersion <= oldVersion) {
            return;
        }
        Configuration.oldVersion = oldVersion;
 
        int changeCnt = newVersion - oldVersion;
        for (int i = 0; i < changeCnt; i++) {
            // 依次执行updatei_i+1文件 由1更新到2 [1-2]，2更新到3 [2-3]
            String schemaName = "update" + (oldVersion + i) + "_"
                    + (oldVersion + i + 1) + ".sql";
            executeAssetsSQL(db, schemaName);
        }
    }
 
    /**
     * 读取数据库文件（.sql），并执行sql语句
     * */
    private void executeAssetsSQL(SQLiteDatabase db, String schemaName) {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(mContext.getAssets()
                    .open(Configuration.DB_PATH + "/" + schemaName)));
 
           System.out.println("路径:" + Configuration.DB_PATH + "/" + schemaName);
            String line;
            String buffer = "";
            while ((line = in.readLine()) != null) {
                buffer += line;
                if (line.trim().endsWith(";")) {
                    db.execSQL(buffer.replace(";", ""));
                    buffer = "";
                }
            }
        } catch (IOException e) {
            Log.e("db-error", e.toString());
        } finally {
            try {
                if (in != null)
                	Log.e("创建数据库", "----->ok");
                    in.close();
            } catch (IOException e) {
                Log.e("db-error", e.toString());
            }
        }
    }
 
    /**
     * 判断是否存在某一张表
     * @param tabName
     * @param db
     * @return
     */
    public boolean tabIsExist(String tabName, SQLiteDatabase db) {
        boolean result = false;
        if (tabName == null) {
            return false;
        }
        Cursor cursor = null;
        try {
            String sql = "select count(*) as c from sqlite_master where type ='table' and name ='" + tabName.trim() + "' ";
            cursor = db.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    result = true;
                }
            }
 
        } catch (Exception e) {
        }
        return result;
    }
    public void closeDB() {
	    if (instance != null) {
	        try {
	            SQLiteDatabase db = instance.getWritableDatabase();
	            db.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        instance = null;
	    }
	}
}
